package city.spring.configure.mybatis.handler;

import city.spring.configure.mybatis.FillCurrentUser;
import city.spring.utils.UserUtils;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;

import java.lang.reflect.Field;

/**
 * MyBatis 自动填充当前用户的一些字段信息
 *
 * @author HouKunLin
 * @date 2020/7/15 0015 15:46
 */
public class CurrentUserMetaObjectHandlerImpl implements IMetaObjectHandler {
    @Override
    public boolean run(MetaObjectHandler metaObjectHandler, MetaObject metaObject, Field field) {
        TableField tableField = field.getAnnotation(TableField.class);
        FillCurrentUser annotation = field.getAnnotation(FillCurrentUser.class);
        if (tableField != null && annotation != null && tableField.fill() == FieldFill.INSERT) {
            if (annotation.value() == FillCurrentUser.Type.OrgId) {
                metaObject.setValue(field.getName(), UserUtils.getOrgId());
            } else {
                metaObject.setValue(field.getName(), UserUtils.getPrincipal().getName());
            }
            return true;
        }
        return false;
    }
}
